<template>
  <div class="app-container">
    <div class="header-section">
      <h1 class="app-title">WoW团队副本周记</h1>
    </div>
    
    <el-table :data="characters" border style="width: 100%">
      <el-table-column prop="name" label="角色" width="180" align="center">
        <template #default="{ row }">
          <div style="display: flex; align-items: center; justify-content: space-between;">
            <span>{{ row.name }}</span>
            <el-icon class="delete-icon" @click.stop="deleteCharacter(row.name)" style="color: #F56C6C; margin-left: 15px">
              <delete />
            </el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-for="raid in raids" :key="raid.id" :label="raid.name" align="center">
        <template #header>
          <div style="text-align: center;">{{ raid.name }}</div>
        </template>
        <template #default="{ row }">
          <div style="display: flex; justify-content: center;">
            <el-checkbox :model-value="raidStatus[raid.id][row.name]" @change="(val) => handleCheckChange({raidId: raid.id, charName: row.name, completed: val})"/>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="table-controls">
      <div class="controls-container">
        <div class="input-group">
          <el-input v-model="newCharName" placeholder="输入角色名" class="char-input" @keyup.enter="addCharacter">
            <template #append>
              <el-button class="add-button" @click="addCharacter" :disabled="!newCharName.trim()">添加角色</el-button>
            </template>
          </el-input>
          <el-button type="danger" @click="showClearConfirm">一键重置CD</el-button>
        </div>
        <div class="reset-date" @click="showResetDialog" title="点击可设置更新日期">下次更新: {{ nextResetDate }}</div>
      </div>
    </div>

    <el-dialog v-model="resetDialogVisible" title="设置更新周期">
      <el-select v-model="selectedResetDay" placeholder="选择更新日">
        <el-option v-for="day in ['周一', '周二', '周三', '周四', '周五', '周六', '周日']" :key="day" :label="day" :value="day"/>
      </el-select>
      <template #footer>
        <el-button @click="resetDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateResetDay">确认</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="addCharDialogVisible" title="添加角色">
      <el-input v-model="newCharName" placeholder="输入角色名" />
      <template #footer>
        <el-button @click="addCharDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addCharacter">确认</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="confirmDialogVisible" :title="confirmDialogTitle" :modal="true" :close-on-click-modal="false" :close-on-press-escape="false">
      <span>{{ confirmDialogMessage }}</span>
      <template #footer>
        <el-button @click="confirmDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAction">确认</el-button>
      </template>
    </el-dialog>

    <div class="footer">
      <div class="copyright">
        <span>© 2025 没头脑的老毕</span>
        <a href="https://space.bilibili.com/25160163" target="_blank" class="social-link bilibili" title="Bilibili主页">
          <img src="@/assets/bilibili.ico" alt="Bilibili" class="bilibili-icon">
        </a>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, provide } from 'vue'
import { ElMessage } from 'element-plus'
import { Delete, ArrowDown } from '@element-plus/icons-vue'
import RaidItem from './components/RaidItem.vue'
import ICC from '@/assets/ICC.jpg'
import RS from '@/assets/RS.jpg'
import TOC from '@/assets/TOC.jpg'
import 宝库 from '@/assets/宝库.jpg'
import 周常 from '@/assets/周常.jpg'

const addCharDialogVisible = ref(false)
const raids = ref([
  { id: '10hicc', name: '10HICC', image: ICC },
  { id: '25hicc', name: '25HICC', image: ICC },
  { id: '10rs', name: '10RS', image: RS },
  { id: '25rs', name: '25RS', image: RS },
  { id: '25toc', name: '25TOC', image: TOC },
  { id: '25htoc', name: '25HTOC', image: TOC },
  { id: '10vault', name: '10宝库', image: 宝库 },
  { id: '25vault', name: '25宝库', image: 宝库 },
  { id: 'weekly', name: '周常', image: 周常 }
])

function initRaidStatus() {
  const status = {}
  raids.value.forEach(raid => {
    status[raid.id] = {}
    characters.value.forEach(char => {
      status[raid.id][char.name] = false
    })
  })
  return status
}

const _loadCharacters = () => {
  try {
    const saved = localStorage.getItem('wow-raid-tracker-chars')
    return saved ? JSON.parse(saved) : []
  } catch (e) {
    return []
  }
}

const characters = ref(_loadCharacters())

const _loadRaidStatus = () => {
  try {
    const saved = localStorage.getItem('wow-raid-tracker-status')
    if (!saved) return {}
    
    const data = JSON.parse(saved)
    const now = new Date()
    const expireDate = new Date(data.expireDate)
    
    if (now >= expireDate) {
      return {}
    }
    
    return data.status || {}
  } catch (e) {
    return {}
  }
}

const raidStatus = ref(_loadRaidStatus())
provide('raidStatus', raidStatus)

const resetDialogVisible = ref(false)
const confirmDialogVisible = ref(false)
const selectedResetDay = ref('周五')
const newCharName = ref('')
const confirmDialogTitle = ref('')
const confirmDialogMessage = ref('')
const pendingAction = ref(null)

const nextResetDate = computed(() => {
  const resetDayMap = {
    '周一': 1, '周二': 2, '周三': 3, '周四': 4,
    '周五': 5, '周六': 6, '周日': 0
  }
  
  const targetDay = resetDayMap[selectedResetDay.value]
  const today = new Date()
  const currentDay = today.getDay()
  
  let daysToAdd = targetDay - currentDay
  if (daysToAdd <= 0) daysToAdd += 7
  
  const nextReset = new Date(today)
  nextReset.setDate(today.getDate() + daysToAdd)
  
  const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  const weekDay = weekDays[nextReset.getDay()]
  
  return `${nextReset.getFullYear()}-${String(nextReset.getMonth() + 1).padStart(2, '0')}-${String(nextReset.getDate()).padStart(2, '0')} ${weekDay}`
})

onMounted(() => {
  loadSavedData()
  
  const checkReset = () => {
    const now = new Date()
    const resetDate = new Date(nextResetDate.value)
    if (now >= resetDate) {
      raidStatus.value = initRaidStatus()
      saveData()
      ElMessage.success('副本CD已自动重置')
    }
  }

  checkReset()
  const timer = setInterval(checkReset, 3600000)
  return () => clearInterval(timer)
})

function loadSavedData() {
  const savedChars = localStorage.getItem('wow-raid-tracker-chars')
  const savedStatus = localStorage.getItem('wow-raid-tracker-status')
  
  try {
    characters.value = savedChars ? JSON.parse(savedChars) : []
    raidStatus.value = _loadRaidStatus()
    
    for (const raidId in raidStatus.value) {
      if (raidStatus.value.hasOwnProperty(raidId)) {
        for (const charName in raidStatus.value[raidId]) {
          if (!characters.value.some(c => c.name === charName)) {
            delete raidStatus.value[raidId][charName]
          }
        }
      }
    }
  } catch (e) {
    characters.value = []
    raidStatus.value = initRaidStatus()
  }
}

function saveData() {
  localStorage.setItem('wow-raid-tracker-chars', JSON.stringify(characters.value))
  
  const resetDayMap = {
    '周一': 1, '周二': 2, '周三': 3, '周四': 4,
    '周五': 5, '周六': 6, '周日': 0
  }
  const targetDay = resetDayMap[selectedResetDay.value]
  const today = new Date()
  const currentDay = today.getDay()
  
  let daysToAdd = targetDay - currentDay
  if (daysToAdd <= 0) daysToAdd += 7
  
  const nextReset = new Date(today)
  nextReset.setDate(today.getDate() + daysToAdd)
  nextReset.setHours(0, 0, 0, 0)
  
  const statusData = {
    expireDate: nextReset.toISOString(),
    status: raidStatus.value
  }
  localStorage.setItem('wow-raid-tracker-status', JSON.stringify(statusData))
}

function handleCheckChange({ raidId, charName, completed }) {
  const originalValue = raidStatus.value[raidId]?.[charName] || false
  showConfirmDialog(
    '确认操作',
    `确认【${charName}】的【${raids.value.find(r => r.id === raidId).name}】${completed ? '已' : '未'}完成吗？`,
    () => {
      if (!raidStatus.value[raidId]) raidStatus.value[raidId] = {}
      raidStatus.value[raidId][charName] = completed
      saveData()
    }
  )
  if (raidStatus.value[raidId]) {
    raidStatus.value[raidId][charName] = originalValue
  }
  return originalValue
}

function showResetDialog() {
  resetDialogVisible.value = true
}

function updateResetDay() {
  resetDialogVisible.value = false
}

function addCharacter() {
  if (!newCharName.value.trim()) return
  
  if (characters.value.some(c => c.name === newCharName.value.trim())) {
    ElMessage.warning('角色已存在')
    return
  }
  
  characters.value.push({
    name: newCharName.value.trim(),
    completed: false
  })
  newCharName.value = ''
  saveData()
  ElMessage.success('角色添加成功')
}

function deleteCharacter(charName) {
  showConfirmDialog(
    '确认删除',
    `确认删除角色【${charName}】吗？`,
    () => {
      characters.value = characters.value.filter(c => c.name !== charName)
      const newRaidStatus = JSON.parse(JSON.stringify(raidStatus.value))
      Object.keys(newRaidStatus).forEach(raid => {
        delete newRaidStatus[raid][charName]
      })
      raidStatus.value = newRaidStatus
      localStorage.setItem('wow-raid-tracker-chars', JSON.stringify(characters.value))
      localStorage.setItem('wow-raid-tracker-status', JSON.stringify(newRaidStatus))
      for (const raidId in raidStatus.value) {
        if (raidStatus.value[raidId][charName]) {
          delete raidStatus.value[raidId][charName]
        }
      }
      saveData()
      ElMessage.success('角色删除成功')
    }
  )
}

function showClearConfirm() {
  showConfirmDialog(
    '确认清空',
    '确认清空所有角色的所有副本的完成情况吗？',
    () => {
      raidStatus.value = initRaidStatus()
      saveData()
      location.reload()
    }
  )
}

function showConfirmDialog(title, message, action) {
  confirmDialogTitle.value = title
  confirmDialogMessage.value = message
  pendingAction.value = action
  confirmDialogVisible.value = true
}

function confirmAction() {
  if (pendingAction.value) pendingAction.value()
  confirmDialogVisible.value = false
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background: linear-gradient(135deg, #0a0a0a 0%, #1a1a1a 50%, #0a0a0a 100%);
  font-family: 'Microsoft YaHei', sans-serif;
}

.app-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  min-height: 100vh;
  background: rgba(10, 10, 10, 0.9);
  border-left: 1px solid #8B4513;
  border-right: 1px solid #8B4513;
}

.header-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
  position: relative;
  padding-bottom: 25px;
  margin-bottom: 40px;
  width: 100%;
}

.header-section::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(to right, transparent, #8B4513, transparent);
}

.app-title {
  color: #FFD700;
  text-align: center;
  margin-bottom: 15px;
  font-size: 2.5em;
  text-shadow: 0 0 10px rgba(255, 215, 0, 0.5);
  letter-spacing: 2px;
  font-weight: bold;
}

.table-controls {
  width: 100%;
  margin-top: 20px;
}

.controls-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.input-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.char-input {
  width: 180px;
}

.char-input .el-input__inner {
  width: 180px !important;
  border-right: none !important;
}

.char-input .el-input-group__append {
  background: transparent;
  border-left: none;
  padding: 0;
}

.char-input .el-input-group__append .el-button {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  border-left: none;
}

.input-group .el-button--danger {
  margin-left: 35px;
}

.reset-date {
  color: #FFD700;
  cursor: pointer;
  font-size: 1.2em;
  padding: 0 10px;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.reset-date:hover {
  color: #FFA500;
}

.add-button {
  background: linear-gradient(145deg, #4CAF50, #2E7D32) !important;
  border-color: #4CAF50 !important;
  color: white !important;
  font-weight: bold;
}

.add-button:hover {
  background: linear-gradient(145deg, #66BB6A, #388E3C) !important;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(76, 175, 80, 0.3);
}

.delete-icon {
  color: #2196F3;
  cursor: pointer;
  margin-left: 15px;
  font-size: 1.2em;
  transition: all 0.3s ease;
}

.delete-icon:hover {
  color: #64B5F6;
  transform: scale(1.2);
}

:deep(.el-button) {
  font-weight: bold;
  letter-spacing: 1px;
  border: 2px solid;
}

:deep(.el-button--primary) {
  background: linear-gradient(145deg, #1e90ff, #0066cc);
  border-color: #1e90ff;
  color: white;
}

:deep(.el-button--danger) {
  background: linear-gradient(145deg, #ff4757, #cc0000);
  border-color: #ff4757;
  color: white;
}

:deep(.el-dialog) {
  background: linear-gradient(145deg, #2a2a2a, #1a1a1a);
  border: 2px solid #8B4513;
  border-radius: 10px;
}

:deep(.el-dialog__header) {
  background: linear-gradient(to right, #8B4513, #D2691E);
  color: #FFD700;
  font-weight: bold;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-input__inner) {
  background: #2a2a2a;
  border: 1px solid #8B4513;
  color: #e6e6e6;
}

:deep(.el-checkbox) {
  margin-left: 10px;  
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #1e90ff;
  border-color: #1e90ff;
}

.el-table {
  --el-table-border-color: #8B4513;
  --el-table-border: 1px solid var(--el-table-border-color);
  --el-table-text-color: #FFD700;
  --el-table-header-text-color: #FFD700;
  --el-table-row-hover-bg-color: rgba(100, 100, 100, 0.2);
  background: linear-gradient(145deg, #1a1a1a, #0a0a0a);
}

.el-table th {
  background: linear-gradient(to right, #5C3A21, #8B4513) !important;
  font-weight: bold;
  border-bottom: 2px solid #5C3A21;
  color: #FFD700;
  backdrop-filter: blur(5px);
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.3);
}

.el-table td {
  background: rgba(30, 30, 30, 0.8);
  border-bottom: 1px solid var(--el-table-border-color);
  color: var(--el-table-text-color);
}

.el-table__body tr:hover > td {
  background: rgba(30, 30, 30, 0.5) !important;
  color: #333 !important;
}

.el-table__body tr:hover > td:first-child {
  background: rgba(30, 30, 30, 0.5) !important;
  color: #333 !important;
}

.el-table__body tr:hover > td .cell {
  color: #333 !important;
}

.el-table .el-table__cell {
  padding: 8px 0;
}

.el-table .el-table__row .el-table__cell:first-child {
  background: rgba(25, 25, 25, 0.9);
  padding-left: 15px;
}

.el-table .el-table__row .el-table__cell:first-child span {
  color: #FFEC8B;
}

.el-table .el-table__row .el-table__cell:not(:first-child) .cell {
  display: flex;
  justify-content: center;
  padding: 0;
  background: transparent;
}

.footer {
  text-align: center;
  margin-top: 30px;
  padding: 15px 0;
  color: #888;
  font-size: 0.9em;
  border-top: 1px solid #444;
}

.copyright {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
}

.social-link.bilibili {
  background-color: rgba(0, 161, 214, 0.1);
  color: #00A1D6;
  border: 1px solid rgba(0, 161, 214, 0.3);
  padding: 8px;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.bilibili-icon {
  width: 24px;
  height: 24px;
  transition: all 0.3s ease;
  object-fit: contain;
}

.social-link.bilibili:hover {
  background-color: rgba(0, 161, 214, 0.2);
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 161, 214, 0.2);
}

.social-link.bilibili:hover .bilibili-icon {
  transform: scale(1.1);
}
</style>
